package com.gln.bloger.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gln.bloger.constant.Constant;
import com.gln.bloger.pojos.Category;
import com.gln.bloger.pojos.Comment;
import com.gln.bloger.pojos.Entry;
import com.gln.bloger.pojos.Tag;
import com.gln.bloger.pojos.User;
import com.gln.bloger.pojos.Website;


public class GuestBaseAction extends BaseAction{
	@SuppressWarnings("unchecked")
	/**
	 * implement dispatchAction's execute method
	 * to put categories into request.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception{
		User user = getAuthUser(request);
		Website website = getAuthWebsite(request);
		
		String handle = (String) request.getParameter("handle");
		String sessionHandle = null ;
		if(website != null){
			sessionHandle = website.getHandle();
		}
		
		/**
		 * if handle changed, the change the web site
		 */
		if(!handle.equals(sessionHandle)){
			website = getWebsiteService().getWebsite(handle);
			this.clearCache();
			request.getSession().setAttribute(Constant.AUTH_WEBSITE, website);
		}
		
		/**
		 * if she/he is not the owner of this web site
		 */
		if(user != null){
			if(!user.isOwner(getAuthWebsite(request))){
				request.getSession().removeAttribute(Constant.AUTH_USER);
			}
		}
		/**
		 * prepare data for display
		 */
		List<Tag> hotTags = getTagService().getHotTags(website);
		List<Category> categories = getCategoryService().getCategoryList(website);
		List<Entry> recentEntries = getEntryService().getRecentEntries(website);
		List<Comment> recentComments = getCommentService().getRecentComments(website);
		List<Date> archivedMonthList = getEntryService().getArchivedMonthList(website);
		
		request.setAttribute("categories", categories);
		request.setAttribute("hotTags", hotTags);
		request.setAttribute("recentEntries", recentEntries);
		request.setAttribute("recentComments", recentComments);
		request.setAttribute("archivedMonthList", archivedMonthList);
		
		return super.execute(mapping, form, request, response);
	}

}
